<!DOCTYPE html>












  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.4.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '6.4.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="有句话说得好：基础不好，代码写不好。（0.0 这话我编的…） 之前对于提到的几个 API 没有很好的理解，趁着今天在使用，所以梳理一下。  静态方法：Class.forName(“xxx”) 的作用 非静态方法 clazz.newInstance() 的作用 直接通过 new的区别">
<meta name="keywords" content="反射">
<meta property="og:type" content="article">
<meta property="og:title" content="Class.forName()和 newInstance() 区别">
<meta property="og:url" content="http://yoursite.com/2018/05/12/forname-newinstance/index.html">
<meta property="og:site_name" content="ThinkMore">
<meta property="og:description" content="有句话说得好：基础不好，代码写不好。（0.0 这话我编的…） 之前对于提到的几个 API 没有很好的理解，趁着今天在使用，所以梳理一下。  静态方法：Class.forName(“xxx”) 的作用 非静态方法 clazz.newInstance() 的作用 直接通过 new的区别">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-07-09T02:48:36.936Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Class.forName()和 newInstance() 区别">
<meta name="twitter:description" content="有句话说得好：基础不好，代码写不好。（0.0 这话我编的…） 之前对于提到的几个 API 没有很好的理解，趁着今天在使用，所以梳理一下。  静态方法：Class.forName(“xxx”) 的作用 非静态方法 clazz.newInstance() 的作用 直接通过 new的区别">






  <link rel="canonical" href="http://yoursite.com/2018/05/12/forname-newinstance/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Class.forName()和 newInstance() 区别 | ThinkMore</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?13172698bcdb7ab00b7d3ec112aae9c1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">ThinkMore</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">驽马十驾,功在不舍！</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />Home</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />Archives</a>
  </li>

      
      
    </ul>
  

  
    

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/05/12/forname-newinstance/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="文敦复">
      <meta itemprop="description" content="思考的懒惰是真的懒惰！">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ThinkMore">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Class.forName()和 newInstance() 区别
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              

              
                
              

              <time title="Created: 2018-05-12 22:11:30" itemprop="dateCreated datePublished" datetime="2018-05-12T22:11:30+08:00">2018-05-12</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Edited on</span>
                
                <time title="Modified: 2018-07-09 10:48:36" itemprop="dateModified" datetime="2018-07-09T10:48:36+08:00">2018-07-09</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">In</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/java基础/" itemprop="url" rel="index"><span itemprop="name">java基础</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>有句话说得好：基础不好，代码写不好。（0.0 这话我编的…）</p>
<p>之前对于提到的几个 API 没有很好的理解，趁着今天在使用，所以梳理一下。</p>
<ul>
<li>静态方法：<code>Class.forName(“xxx”)</code> 的作用</li>
<li>非静态方法 <code>clazz.newInstance()</code> 的作用</li>
<li>直接通过 <code>new</code>的区别</li>
</ul>
<a id="more"></a>
<h1 id="Class-forName-“xxx”"><a href="#Class-forName-“xxx”" class="headerlink" title="Class.forName(“xxx”)"></a>Class.forName(“xxx”)</h1><h2 id="作用"><a href="#作用" class="headerlink" title="作用"></a>作用</h2><p>老规矩，先上代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Class&lt;?&gt; clazz = Class.forName(<span class="string">"club.hicode.daydayup.reflect.RefPerson"</span>);</span><br></pre></td></tr></table></figure>
<p>从上述代码可以看出3点：</p>
<ol>
<li><code>forName</code> 是一个<code>Class</code>的静态方法，通过<code>Class</code> 直接调用。</li>
<li><code>forName</code> 中需要给出一个 <code>全路径的包+类</code> </li>
<li><code>forName</code>返回值是一个 <code>Class</code>对象。</li>
</ol>
<p>这个 API 有什么作用了？</p>
<p>如果要了解静态方法<code>Class.forName(“xxx”)</code>  的作用，需要了解JVM 中类的加载机制，这里不展开讲。</p>
<p>简单而言就是要使用某一个类，那么必须先从 <code>.class</code> 的二进制文件加载到<code>JVM</code>中。<code>forname</code> 就是起到的就是这个作用。</p>
<blockquote>
<p>这个时候你可能会想，我们平时在使用的时候是直接 new 的，没有通过 forName，那是不是就没有加载类了？</p>
<p>请保留这个疑问，继续往下看，后续的 new 的部分会解答这个疑问。</p>
</blockquote>
<h2 id="扩展"><a href="#扩展" class="headerlink" title="扩展"></a>扩展</h2><p>我们通过代码测试下，假如有一个RefPerson 类，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RefPerson</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">"RefPerson static init..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">RefPerson</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">"RefPerson init..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>核心测试代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refTest0</span><span class="params">()</span> <span class="keyword">throws</span> ClassNotFoundException </span>&#123;</span><br><span class="line">    Class&lt;?&gt; clazz = Class.forName(<span class="string">"club.hicode.daydayup.reflect.RefPerson"</span>);</span><br><span class="line">    System.out.println(clazz);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其输出如下所示:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">RefPerson static init...</span><br><span class="line">class club.hicode.daydayup.reflect.RefPerson</span><br></pre></td></tr></table></figure>
<p>大家发现没有，输出的是2行，这个分别是什么？</p>
<ol>
<li>第一行<code>RefPerson static init...</code> 是因为<code>RefPerson</code>中有一个<strong>静态代码块</strong>，该语句是在静态代码块中被执行的。由此可以发现：<code>forName</code>的时候会执行<strong>静态代码块</strong>中的内容，这个也是很多时候我们在写 JDBC 的时候会用到的，比如如下代码：</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Class.forName(<span class="string">"com.mysql.jdbc.Driver"</span>);</span><br></pre></td></tr></table></figure>
<p>​    这个代码其核心执行的其实是<code>com.mysql.jdbc.Driver</code>这个类的静态代码块中的代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Driver</span> <span class="keyword">extends</span> <span class="title">NonRegisteringDriver</span> <span class="keyword">implements</span> <span class="title">java</span>.<span class="title">sql</span>.<span class="title">Driver</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Driver</span><span class="params">()</span> <span class="keyword">throws</span> SQLException </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            DriverManager.registerDriver(<span class="keyword">new</span> Driver());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (SQLException var1) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"Can't register driver!"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>就是 static 这个里面的代码。</p>
<ol start="2">
<li>第二行输出的就是加载的类。</li>
</ol>
<h1 id="clazz-newInstance"><a href="#clazz-newInstance" class="headerlink" title="clazz.newInstance()"></a>clazz.newInstance()</h1><h2 id="作用-1"><a href="#作用-1" class="headerlink" title="作用"></a>作用</h2><p>该方法通常会和<code>Class.forName()</code>搭配使用，如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refTest3</span><span class="params">()</span> <span class="keyword">throws</span> ClassNotFoundException, IllegalAccessException, InstantiationException </span>&#123;</span><br><span class="line">    Class&lt;?&gt; clazz = Class.forName(<span class="string">"club.hicode.daydayup.reflect.RefPerson"</span>);</span><br><span class="line">    RefPerson refPerson = (RefPerson) clazz.newInstance();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>通过加载到 JVM中的 Class 对象调用<code>newInstance()</code> 进行具体实例的初始化。</p>
<h2 id="扩展-1"><a href="#扩展-1" class="headerlink" title="扩展"></a>扩展</h2><p>上述代码的输出是什么？</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">RefPerson static init...</span><br><span class="line">RefPerson init...</span><br></pre></td></tr></table></figure>
<ol>
<li>第一行是 forName 加载类的时候，调用的静态代码块中的输出的。</li>
<li>第二行是<code>RefPerson</code>的<code>无参构造函数</code>中输出的。</li>
</ol>
<p>这个地方有一个细节：</p>
<p><code>clazz.newInstance()</code>其实会反射调用<code>clazz</code>对应类的无参构造函数，如果没有无参构造函数那么就会出报错:<code>ClassNotFoundException</code>。</p>
<p>这个地方再扩展个内容，如果当前代码不具有无参的构造函数，又想反射调用，怎么办？</p>
<h2 id="缺失无参构造函数的时候初始化"><a href="#缺失无参构造函数的时候初始化" class="headerlink" title="缺失无参构造函数的时候初始化"></a>缺失无参构造函数的时候初始化</h2><p>假如RefPerson 改为如下所示：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RefPerson</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        System.out.println(<span class="string">"RefPerson static init..."</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 这有这个有参的构造函数</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">RefPerson</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li>引入如下 xml</li>
</ol>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.objenesis<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>objenesis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.6<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ol start="2">
<li>通过如下代码使用</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refTest4</span><span class="params">()</span> <span class="keyword">throws</span> ClassNotFoundException </span>&#123;</span><br><span class="line">    Class&lt;?&gt; clazz = Class.forName(<span class="string">"club.hicode.daydayup.reflect.RefPerson"</span>);</span><br><span class="line">    <span class="comment">// 这个地方</span></span><br><span class="line">    org.objenesis.Objenesis objenesis = <span class="keyword">new</span> org.objenesis.ObjenesisStd(<span class="keyword">true</span>);</span><br><span class="line">    RefPerson refPerson = (RefPerson) objenesis.newInstance(clazz);</span><br><span class="line">    System.out.println(refPerson);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其实如果已经引入<code>Spring</code>那么它自身就已经具有了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">refTest5</span><span class="params">()</span> <span class="keyword">throws</span> ClassNotFoundException </span>&#123;</span><br><span class="line">    Class&lt;?&gt; clazz = Class.forName(<span class="string">"club.hicode.daydayup.reflect.RefPerson"</span>);</span><br><span class="line">    org.springframework.objenesis.Objenesis objenesis = <span class="keyword">new</span> org.springframework.objenesis.ObjenesisStd(<span class="keyword">true</span>);</span><br><span class="line">    RefPerson refPerson = (RefPerson) objenesis.newInstance(clazz);</span><br><span class="line">    System.out.println(refPerson);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>输出为：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">RefPerson static init...</span><br><span class="line">RefPerson(name=null, age=null)</span><br></pre></td></tr></table></figure>
<h1 id="new-使用"><a href="#new-使用" class="headerlink" title="new 使用"></a>new 使用</h1><p>其实 new 是当明确了类的时候使用的，其作用等价于：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Class.forName(<span class="string">"xxx.xxx"</span>).newInstance();</span><br></pre></td></tr></table></figure>
<p>new 的时候也会触发2个操作：</p>
<ol>
<li>加载 Class 到方法区</li>
<li>创建对象</li>
</ol>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>这3个东西，分别何时使用了？</p>
<ol>
<li>Class.forName 的一个典型使用就是 在静态代码块中 注入 SQL 驱动，在上面文章已经讲过了。</li>
<li>clazz.newInstance 是通过反射创建对象，是实现IOC、反射、面对接口编程和依赖倒置等技术方法的必然选择，通常框架会使用，使我们代码更加灵活。</li>
<li>new 明确了使用类的时候，直接通过 new，最简单、方便、快捷。缺点就是不够灵活。</li>
</ol>
<blockquote>
<p>您有任何建议和意见，请Email联系: <a href="mailto:hicode_club@163.com" target="_blank" rel="noopener">hicode_club@163.com</a></p>
<p>转载请保留出处 <a href="http://www.hicode.club" target="_blank" rel="noopener">HiCode 俱乐部</a></p>
</blockquote>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/05/02/protostuff/" rel="next" title="更简单的使用protobuf---protostuff">
                <i class="fa fa-chevron-left"></i> 更简单的使用protobuf---protostuff
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/05/27/classloader/" rel="prev" title="Java类加载器--ClassLoader">
                Java类加载器--ClassLoader <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">文敦复</p>
              <p class="site-description motion-element" itemprop="description">思考的懒惰是真的懒惰！</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">39</span>
                    <span class="site-state-item-name">posts</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">37</span>
                    <span class="site-state-item-name">categories</span>
                  
                </div>
              

              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Class-forName-“xxx”"><span class="nav-number">1.</span> <span class="nav-text">Class.forName(“xxx”)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#作用"><span class="nav-number">1.1.</span> <span class="nav-text">作用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#扩展"><span class="nav-number">1.2.</span> <span class="nav-text">扩展</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#clazz-newInstance"><span class="nav-number">2.</span> <span class="nav-text">clazz.newInstance()</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#作用-1"><span class="nav-number">2.1.</span> <span class="nav-text">作用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#扩展-1"><span class="nav-number">2.2.</span> <span class="nav-text">扩展</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#缺失无参构造函数的时候初始化"><span class="nav-number">2.3.</span> <span class="nav-text">缺失无参构造函数的时候初始化</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#new-使用"><span class="nav-number">3.</span> <span class="nav-text">new 使用</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文敦复</span>

  

  
</div>




  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme – <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Muse</a> v6.4.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
	
    

    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.0"></script>



  



  










  





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
